package blockchain

import (
	"context"
	"strconv"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzblockchainwalletrecord"

	"github.com/samber/lo"
	"github.com/zeromicro/go-zero/core/logx"
)

type BlockchainApprovalListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 后台审批列表
func NewBlockchainApprovalListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BlockchainApprovalListLogic {
	return &BlockchainApprovalListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BlockchainApprovalListLogic) BlockchainApprovalList(req *types.BlockchainApprovalListRequest) (resp *types.BlockchainApprovalListResponse, err error) {
	// 初始化响应结构
	resp = &types.BlockchainApprovalListResponse{
		List: make([]*types.TransferRecord, 0),
	}

	// 构建查询条件
	query := l.svcCtx.Orm.HzBlockchainWalletRecord.Query()

	// 获取总数
	total, err := query.Count(l.ctx)
	if err != nil {
		logx.Errorf("获取区块链记录总数失败: %v", err)
		return nil, err
	}

	// 分页查询数据
	records, err := query.
		Offset(int((req.Current - 1) * req.PageSize)).
		Limit(int(req.PageSize)).
		Order(ent.Desc(hzblockchainwalletrecord.FieldID)).
		All(l.ctx)
	if err != nil {
		logx.Errorf("查询区块链记录失败: %v", err)
		return nil, err
	}

	// 转换数据格式
	resp.List = lo.Map(records, func(record *ent.HzBlockchainWalletRecord, _ int) *types.TransferRecord {
		// 获取用户手机号
		phone := func() string {
			user, err := l.svcCtx.Orm.HzUser.Get(l.ctx, int(record.UserID))
			if err != nil {
				logx.Errorf("获取用户手机号失败: %v", err)
				return ""
			}
			return user.UserPhone
		}()

		// 获取钱包地址
		to := func() string {
			wallet, err := l.svcCtx.Orm.HzBlockchainWallet.Get(l.ctx, int(record.BlockchainWalletID))
			if err != nil {
				logx.Errorf("获取钱包地址失败: %v", err)
				return ""
			}
			return wallet.WalletAddress
		}()

		return &types.TransferRecord{
			BlockCredentials:  record.RecordNumber,
			CreateTime:        strconv.FormatInt(record.CreatedAt, 10),
			SpendPoints:       strconv.FormatInt(record.RecordIntegralAmount, 10),
			FeeRates:          float64(record.RecordRates),
			GasFees:           int(record.RecordServiceCharge),
			HzbAmounts:        int(record.RecordHzbCoin),
			Phone:             phone,
			To:                to,
			PayoutStatus:      int(record.RecordStatus),
			TransferStatus:    int(record.RecordTransferStatus),
			RecordRejectCause: record.RecordRejectCause,
			PassTime:          strconv.FormatInt(record.RecordPassTime, 10),
			ArrivedTime:       strconv.FormatInt(record.RecordArrivedTime, 10),
			RejectTime:        strconv.FormatInt(record.RecordRejectTime, 10),
		}
	})

	// 设置分页信息
	resp.Page = &types.PageResponse{
		Current:  req.Current,
		PageSize: req.PageSize,
		Total:    int64(total),
	}

	return resp, nil
}
